package src;

import java.sql.*;
import src.Players.Player;
import src.MD5;

public class SQL {
	private Player p;
	public static String MySQLURL = "jdbc:mysql://nyoxis.org/a4237811_vb";
	public static String MySQLUser = "a4237811_v";
	public static String MySQLPassword = "lol123";
	public static Connection conn;
	
	SQL() {
		System.out.println("creating connection to database...");
		createConnection();
	}
	
	public static void createConnection(){
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			conn = DriverManager.getConnection(MySQLURL, MySQLUser, MySQLPassword);
			System.out.println("mysql connected");
		} catch(Exception e) {	
			e.printStackTrace();
		}
	}
	
	public String passHash(String in, String salt){
		String a = new MD5(in).compute();
		String b = new MD5(a + salt).compute();
		return b;
	}
	public MD5 md5(String a) {
		MD5 b = new MD5(a);
		return b;
	}

	public boolean Load(String Password) {
		try {
			Statement statement = this.conn.createStatement();
			ResultSet group = statement.executeQuery("SELECT * FROM user WHERE username = '"+p.username+"'");
			while(group.next()) {
				String pass = group.getString("password");
				String salt = group.getString("salt");
				String passe = passHash(Password, salt);
				if(pass.equalsIgnoreCase(passe)) {
				} else { 
					statement.close();
					return false; 
				}
			}	
			ResultSet group2 = statement.executeQuery("SELECT * FROM user WHERE username = '"+p.username+"'");
			while(group2.next()) {
				String groupp2 = group2.getString("usergroupid");
				int mgroup = Integer.parseInt(groupp2);
				if(mgroup == 6) {
					return true;
				} else if(mgroup == 9) {
					//Silenced = true;
					statement.close();
					return true;
				} 
			}
			return true;
		} catch (Exception sqlEx){	
			try{
				this.conn.close();
				this.createConnection();
			} catch (Exception sqlEx2){}
				return false;
			}
	}
}